Programming III - Loops, conditionals, & OOP
GEOG 30323
September 13, 2018
Python refresher
- Exercise available in CoCalc
Iteration

Iteration
- At your jobs, you will often need to repeat the same task over and over!
- From your textbook: “Repeating identical or similar tasks without making errors is something that computers do well and people do poorly.”
- Solution: make the computer do it with iteration
Loops
- Loops are operators that tell the computer to repeat an action a given number of times
- Common loops:
for: Repeats an action over a series of items
while: Repeats an action until a given condition is satisfied
- Important note: loops, like functions, must obey whitespace rules!
The for loop
for repeats an action for every element in an object
- Example:
How for works
So what is going on here?
- The
for loop looks at what it will iterate through - in this case it is a string, Kyle
- We are referring to each element of our string,
Kyle, as character.
- The loop evaluates the expression passed to the
print function for each character in Kyle successively
So the for loop is equivalent to:
The while loop
while repeats an action until a given condition is satisfied
- Example:
How while works
- We define a counter,
i, that we set to 5 before running the loop
- While the value of
i is greater than 0, we tell Python to evaluate the print function
- With each run of the loop, we subtract
1 from i
- When
i is equal to 0, we exit the loop and print "Blast-off" to the console
Beware of the infinite while loop!
Conditional logic
- However - what if we don’t want to do the same thing every time we run a loop? Or a function, for that matter?
- Answer: conditional logic
Conditional logic
- Conditional statements in Python:
if, elif, and else
- Conditional operators:
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Is equal to
!= Is not equal to
- Booleans:
True and False
- Boolean operators:
and, or, & not
Conditional logic in Python
Conditional logic in functions
- When writing functions, you’ll rely heavily on conditional statements
Object-oriented programming
- Programming paradigm in which language is oriented around data objects
- In Python, “everything is an object!”
Classes
- A class is a special type of Python object that itself can have attributes and methods
- Associated with object-oriented programming in Python
Class attributes and methods
- Class attributes: attributes that are associated with a given class
- Attributes can be associated with the class or class instances
- Class methods: functions associated with the class